/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-02-21
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-04-16
 * @Description: 
 */

import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:image_picker/image_picker.dart' show XFile;

// 路由
import 'package:chat_client/router/router.dart';
import 'package:chat_client/screens/mobile/individual/avatar_preview.dart';
import 'package:chat_client/screens/mobile/individual/setting.dart';
import 'package:chat_client/screens/mobile/individual/update.dart';
import 'package:chat_client/repositories/hive_view_page.dart';

// 服务
import 'package:chat_client/services/user_service.dart';
// 配置
import 'package:chat_client/config/api_config.dart';
import 'package:chat_client/enums/user_enum.dart';
// 仓库
import 'package:chat_client/models/user_model.dart';
import 'package:chat_client/repositories/hive_repository.dart';
// 组件
import 'package:chat_client/widgets/c_loading.dart';
//工具
import 'package:chat_client/utils/validation.dart';
import 'package:chat_client/utils/image-picker/image_picker_helper.dart';
import 'package:chat_client/utils/date_formater.dart';
import 'package:chat_client/utils/show_messae.dart';

class IndividualProvider extends ChangeNotifier {
  final UserService userService = UserService.instance;
  final HiveService hive = HiveService.instance;

  final TextEditingController captchaController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();
  final TextEditingController oldPasswordController = TextEditingController();

  // 个人信息
  late User _user;
  // 个人信息列表项

  String? _captchaUid;

  // 对外暴露不可变引用
  User get user => _user;
  String get avatarUrl => AppConfig.baseUrl + _user.avatarUrl;

  // 构造函数中同步初始化
  IndividualProvider() {
    _initializeUser();
  }
  // 初始化Uer
  Future<void> _initializeUser() async {
    _user = userService.getLocalUserInfo();
    notifyListeners();
  }

  /// update 页面
  // 更新头像
  Future<void> pickImageToUpdate() async {
    try {
      final XFile? file = await ImagePickerHelper.pickAndProcessImage();
      if (file == null) return;
      // 更新头像，自动更新本地仓库
      await userService.updateAvatar(file);
      // 格重新拉取本地信息
      _initializeUser();
      notifyListeners();
    } catch (e) {
      print('图片处理失败${e.toString()}');
    }
  }

  // 用户信息更新
  Future<void> updateUser<T>(
      {required String type,
      required T newInfo, // 强制指定类型
      T? oldInfo,
      bool goback = true}) async {
    if (newInfo == oldInfo) return;
    try {
      Loading.show(message: "正在更新...");
      await userService.updateUserInfo({type: newInfo});
      _initializeUser();
      notifyListeners();
      if (goback) RouteManager.goBack();
    } catch (e) {
      popError(e.toString(), '修改失败');
    } finally {
      Loading.hide();
    }
  }

  // 用户注销
  deleteUser() async {
    final captchaCode = captchaController.text.trim();
    final password = passwordController.text.trim();
    Loading.show(message: "正在注销...");

    try {
      final isOked = await userService.logout(
        password: password,
        captchaCode: captchaCode,
        captchaUid: _captchaUid!,
      );
      if (isOked) {
        popMessage('注销成功');
        // 账号登出
        await logout();
      } else {
        popError('请稍后重试', '注销账号失败');
      }
    } catch (e) {
      popError(e.toString(), '注销账号失败');
    } finally {
      Loading.hide();
    }
  }

  // 用户更新密码
  passwordUpdate(BuildContext context) async {
    Loading.show(message: "正在更新密码...");
    final newPassword = passwordController.text.trim();
    final oldPassword = oldPasswordController.text.trim();
    final captchaCode = captchaController.text.trim();

    // 登录校验
    String? errorText = validateUpdatePassword(
      oldPassword: oldPassword,
      password: newPassword,
    );

    if (errorText != null) {
      popError(errorText, '更新密码失败');
      Loading.hide();
      return;
    }

    try {
      final isOked = await userService.changePassword(
        oldPassword: oldPassword,
        newPassword: newPassword,
        captchaCode: captchaCode,
        captchaUid: _captchaUid!,
      );
      if (!context.mounted) return;
      if (isOked) {
        popMessage('密码修改成功');
        // 账号登出
        await logout();
      } else {
        popError('请稍后重试', '更新密码失败');
      }
    } catch (e) {
      if (!context.mounted) return;
      popError(e.toString(), '更新密码失败');
    } finally {
      Loading.hide();
    }
  }

  /// 路由转跳
  // mobile头像预览
  navToAvatar() {
    RouteManager.navigateToWidget(
        ImagePreviewPage(updateAvatar: pickImageToUpdate));
  }

  // mobile 个人信息
  navToProfile() {
    RouteManager.navigateToWidget(MobileUserInfoPage());
  }

  // mobile settings
  navToSetting() {
    RouteManager.navigateToWidget(MobilesSettingPage());
  }

  // 登出 login screen
  Future<void> logout() async {
    try {
      await HiveService.instance.resetAll();
      RouteManager.replaceWith(kIsWeb ? '/web-login' : '/mobile-login');
    } catch (e) {
      popError('hive_db 不存在', '登出失败');
    }
  }

  //
  navToWidget(Widget page) {
    RouteManager.navigateToWidget(page);
  }

  /// 其它方法

  void handleCaptchaUidChanged(String? uid) {
    _captchaUid = uid;
  }

  // 获取性别对应的文字标签
  String getGenderLabel(int gender) {
    return GenderEnum.fromInt(gender).label;
  }

  // 添加权限标签
  String getAddTypeLabel(int type) {
    return UserAddType.fromInt(type).label;
  }

  // 注册时间标准格式
  String getDateFormat(time) {
    return getLocalTimeYYMMDD(time);
  }

  /// 临时
  navToHiveView() {
    RouteManager.navigateToWidget(HiveVisualScreen());
  }

  clearHive() {
    HiveService.instance.resetAll();
  }
}
